#include<vector>
#include<iostream>
#include<algorithm>

using namespace std;


class Solution
{
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target)
    {
        vector<vector<int>> ans;
        sort(nums.begin(), nums.end());
        int len = nums.size();
        for (int i = 0; i < len - 3;)
        {
            for (int j = i + 1; j < len - 2;)
            {
                int left = j + 1;
                int right = len - 1;
                int sum = nums[left] + nums[right];
                int newtarget = target - nums[i] - nums[j];
                if (sum < newtarget) left++;
                else if (sum > newtarget) right--;
                else {
                    ans.push_back({ nums[i], nums[j], nums[left], nums[right] });
                    left++, right--;
                    while (left < right && nums[left] == nums[left - 1]) left++;
                    while (left < right && nums[right] == nums[right + 1]) right--;
                }
                j++;
                while (j < len - 2 && nums[j] == nums[j - 1]) j++;
            }
            i++;
            while (i < len - 3 && nums[i] == nums[i - 1]) i++;
        }
        return ans;
    }
};
